import Vue from 'vue'
import { asyncPost } from '~/api/ajax'

let onBridgeReady
const wxShare = {
  install(Vue) {
    Vue.prototype.wxShare = async (config = {}, referrerId) => {
      await watchHasWeixinJSBridge()
      console.log('1111111111')
    
      const PAGE_HREF = location.href
      let homeHref = sessionStorage.getItem('homeHref') || location.href
      let href = isIos() ? homeHref : location.href
    
      const resp = await asyncPost(`/api/auth/weixin/wxShareConfig`, {url: href})
    
      const { appId, timestamp, noncestr: nonceStr, signature } = resp || {}
    
      console.log('cfg:', resp)
      wx.config({
        debug: false,
        appId,
        timestamp,
        nonceStr,
        signature,
        jsApiList: [
          'hideAllNonBaseMenuItem',
          'showAllNonBaseMenuItem', 
          'updateAppMessageShareData', 
          'updateTimelineShareData',
          'onMenuShareAppMessage',
          'onMenuShareTimeline'
        ]
      })
    
      toggleMenuShow(false)
      wx.error(res => {})
    
      const appMessage = isIos() ? 'updateAppMessageShareData' : 'onMenuShareAppMessage'
      const timeline = isIos() ? 'updateTimelineShareData' : 'onMenuShareTimeline'
      wx.ready(() => {
        toggleMenuShow(true)
    
        let [pageQuery, pageNoQuery] = [(PAGE_HREF || '').split('?')[1] || '', (PAGE_HREF || '').split('?')[0]]
        if (pageQuery.includes('referrerId')) {
          pageQuery = pageQuery.split('&').filter(item => !item.includes('referrerId')).join('&')
        }
        let link = `${pageNoQuery}?referrerId=${referrerId}` + (pageQuery ? `&${pageQuery}` : '')
        let isLinkHasToken = /token|login/gi.test(link)
        if (isLinkHasToken) link = `${location.protocol}//${location.host}`
    
        wx[appMessage](Object.assign({}, config, {
          link,
          success () { }
        }))
        wx[timeline](Object.assign({}, config, {
          link,
          success () { }
        }))
      })
      
    }
  }
}

function watchHasWeixinJSBridge(params) {
  if (window.WeixinJSBridge) return Promise.resolve()
  return new Promise(resolve => {
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
      resolve()
      document.removeEventListener('WeixinJSBridgeReady', onBridgeReady)
    })
  })
}
function isIos() {
  return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
}
function toggleMenuShow(isShow) {
  // WeixinJSBridge.call(isShow ? 'showOptionMenu' : 'hideOptionMenu')
  const action = isShow ? 'showAllNonBaseMenuItem' : 'hideAllNonBaseMenuItem'
  wx.ready(() => {
    wx[action]();
  })
}

Vue.use(wxShare)

